

package com.hit.common.security.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hit.admin.api.dto.UserDTO;
import com.hit.admin.api.dto.UserInfo;
import com.hit.admin.api.entity.SysUser;
import com.hit.admin.api.service.SysUserService;
import com.hit.common.core.constant.CacheConstants;
import com.hit.common.core.exception.ErrorCodes;
import com.hit.common.core.util.MsgUtils;
import com.hit.common.core.util.R;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 用户详细信息
 *
 * @author kehanjiang hccake
 */
@Slf4j
@Primary
@RequiredArgsConstructor
public class HitUserDetailsServiceImpl implements HitUserDetailsService {

    private final SysUserService userService;

    private final CacheManager cacheManager;

    /**
     * 用户名密码登录
     *
     * @param username 用户名
     * @return
     */
    @Override
    @SneakyThrows
    public UserDetails loadUserByUsername(String username) {
        Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
        if (cache != null && cache.get(username) != null) {
            return (HitUser) cache.get(username).get();
        }

        UserDTO userDTO = new UserDTO();
        userDTO.setUsername(username);
        R<UserInfo> result = this.info(userDTO);
        UserDetails userDetails = getUserDetails(result);
        if (cache != null) {
            cache.put(username, userDetails);
        }
        return userDetails;
    }

    private R<UserInfo> info(UserDTO userDTO) {
        String username = userDTO.getUsername();
        String phone = userDTO.getPhone();
        SysUser user = userService.getOne(Wrappers.<SysUser>query()
                .lambda()
                .eq(StrUtil.isNotBlank(username), SysUser::getUsername, username)
                .eq(StrUtil.isNotBlank(phone), SysUser::getPhone, phone));
        if (user == null) {
            return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_USERINFO_EMPTY, username));
        }
        return R.ok(userService.findUserInfo(user));
    }


    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }

}
